package com.xiaoxi.exam.service;

import com.xiaoxi.exam.consts.Const;
import com.xiaoxi.exam.model.PreOrder;
import com.xiaoxi.exam.model.ToeflOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;

//@Component
@Slf4j
public class BookService {

    private static Semaphore SEMAPHORE = new Semaphore(5);

    @Autowired
    @Qualifier("bookExecutorService")
    private ExecutorService executorService;
    @Autowired
    private OrderService orderService;

    @Async
    public void startBook(PreOrder order) {
        boolean success = false;
        try {
            success = SEMAPHORE.tryAcquire(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (success) {
            List<ToeflOrder> toeflOrders = orderService.getToeflOrderListByOrderId(order.getId());
            if (!toeflOrders.isEmpty()) {
                String city = toeflOrders.get(0).getCity();
                Set<String> schools = new HashSet<>();
                Set<String> dates = new HashSet<>();
                toeflOrders.forEach(o -> {
                    schools.add(o.getSchool());
                    dates.add(o.getDate());
                });
                Future<String> submit = executorService.submit(new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        return null;
                    }
                });
                try {
                    String s = submit.get();
                } catch (InterruptedException | ExecutionException e) {
                    Const.NEED_BOOK_ORDER.offer(order);
                    log.info("book failed, reoffer in queue {}", order);
                } finally {
                    SEMAPHORE.release();
                }
            }
        } else {
            Const.NEED_BOOK_ORDER.offer(order);
        }
    }
}
